<?php

namespace App\Listeners\Train;

use App\Events\Train\TicketQueryEvent;
use App\Models\Trip\History\Repositories\Interfaces\TripQueryHistoryRepositoryInterface;
use App\Trip\Orders\TripType;
use App\Trip\Train\TrainQueryFromToData;
use Exception;
use Illuminate\Support\Facades\Log;

class TicketQueryListener
{

    private $repo;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        $this->repo = app(TripQueryHistoryRepositoryInterface::class);
    }

    /**
     * Handle the event.
     *
     * @param object $event
     * @return void
     */
    public function handle(TicketQueryEvent $event)
    {
        $data = $event->data;
        if (!isset($data['user'])) {
            return;
        }
        /**
         * @var TrainQueryFromToData $from
         * @var TrainQueryFromToData $to
         */
        $user_id = $data['user']->getUserId() ?: '';
        $from    = $data['from'];
        $to      = $data['to'];
        try {
            if ($user_id) {
                // 添加到历史记录
                $this->repo->addByUserId($user_id, [
                    'trip_type'  => TripType::TRIP_TYPE_TRAIN,
                    'from_type'  => $from->getType(),
                    'to_type'    => $to->getType(),
                    'from_code'  => $from->getCode(),
                    'to_code'    => $to->getCode(),
                    'updated_at' => $data['updated_at'] ?? '',
                ]);
            }
        } catch (Exception $e) {
            Log::error("TicketQueryListener:{$e->getFile()},{$e->getMessage()},{$e->getLine()}");
        }
    }
}
